// 获取文章
import pool from '@/server/db'
import { RowDataPacket } from 'mysql2'
import joi from 'joi'

const schema = joi.object({
  pageSize: joi.string().required(),
  page: joi.string().required(),
})

export default defineEventHandler(async event => {
  // get方法只能传字符串类型的参数，getQuery方法返回的对象中的键值对也是字符串类型的
  interface QueryParams {
    pageSize: string
    page: string
  }
  const query: QueryParams = await getQuery(event)

  // 判断用户是否登录
  if (!event.context.userinfo) return r('请登录')
  const { uid } = event.context.userinfo

  // 数据校验
  try {
    schema.validate(query)
  } catch (error) {
    return r('数据校验错误 ' + error)
  }

  // 查询文章
  try {
    const { pageSize, page } = query
    const offset = Number(pageSize) * (Number(page) - 1)
    const [rows] = await pool.query(
      'SELECT * FROM `notes` WHERE `uid` = ? LIMIT ? OFFSET ?',
      [uid, Number(pageSize), offset]
    )
    if ((rows as RowDataPacket[]).length < 1) {
      return r('查询文章失败')
    }
    return r('查询成功', 1, rows)
  } catch (error) {
    return r('文章查询失败:' + error)
  }
})
